/*
 * Copyright@www.it1997.com.
 * @Author: 陈晓晨
 * @Date: 2020/6/4
 * Description:版权所有 QQ:376231445
 */

package com.it1997.it1997admin.service.impl;

import com.it1997.it1997admin.mapper.PermissionMapper;
import com.it1997.it1997admin.pojo.Permission;
import com.it1997.it1997admin.service.PermissionService;
import com.it1997.it1997admin.vo.PermissionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class PermissionServieImpl implements PermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public List<Permission> getPermissionList(Integer roleId) {
        return permissionMapper.getPermissionList(roleId);
    }

    @Override
    public List<Permission> getChildPermissions(Integer pid,Integer roleId) {
        return permissionMapper.getChildPermissions(pid,roleId);
    }

    @Override
    public List<PermissionVo> getChildPermissions(Integer pid) {
        return permissionMapper.getAllChildPermissions(pid);
    }

    @Override
    public List<Permission> getPermissionList(List<Permission> rootPermissionList,Integer roleId) {
            for (Permission permission : rootPermissionList){
                queryChildPermission(permission,roleId);
            }
            return rootPermissionList;
    }

    @Override
    public int addPermission(String permissionList,int roleId) {
        try {
            //将权限分割成数组
            String[] perArray = permissionList.split(",");
            for (String s:perArray){
              //新增权限
                System.out.println("权限id："+s);
                int i=permissionMapper.addPermission(s,roleId);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return 0;
    }
    @Override
    public List<PermissionVo> getAllPermission(List<PermissionVo> rooPermissionList) {
        for (PermissionVo permissionVo:rooPermissionList){
            queryChildPermission(permissionVo);
        }
        return rooPermissionList;
    }
    /*
* 运用递归 查询出子权限
* */
    private void queryChildPermission(Permission parent,Integer roleId){
        List<Permission> childPermissionList= permissionMapper.getChildPermissions(parent.getId(),roleId);
        for(Permission parentPermission:childPermissionList){
            queryChildPermission(parentPermission,roleId);
        }
        parent.setChild(childPermissionList);
    }
    private void queryChildPermission(PermissionVo parent){
        List<PermissionVo> childPermissionList= permissionMapper.getAllChildPermissions(parent.getId());
        for(PermissionVo parentPermission:childPermissionList){
            queryChildPermission(parentPermission);
        }
        parent.setChildren(childPermissionList);
    }
}
